# -*- coding: utf-8 -*-
#    Copyright 2005 Spike^ekipS <spikeekips@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import gc
import logging

from twisted.web import xmlrpc
from twisted.internet import reactor
reactor.suggestThreadPoolSize(10)

#import threadpool
from thread__ import futurethread
from logger import initLog
from util import datetime__
import database
from model.channel import Channel as model_channel
from model.status import Status as model_status
from model.channel_entry import ChannelEntry as model_channel_entry
from model.tmp_channel import TmpChannel as model_tmp_channel

from document import channel as document_channel

import config

THREAD = futurethread.Thread
QUERY_INSERT_INTO_TMP_CHANNEL_WIERD = \
"""INSERT INTO
	tmp_channel
(
	SELECT
		id, id, NULL, NULL
	FROM
		channel
	WHERE
		id NOT IN (
			SELECT
				channel_id
			FROM
				status
		)
)"""
QUERY_INSERT_INTO_TMP_CHANNEL = \
"""INSERT INTO
	tmp_channel
(
	SELECT
		channel_id AS id,
		channel_id,
		time_updated,
		status
	FROM
		status
	where
		(time_updated < '%s' OR time_updated IS NULL ) AND
		( status in (200) or status IS NULL)
	ORDER BY
		channel_id
)"""


class ZZimClient (THREAD) :
	"""
	It's simple task.
		1. read the channel list from agu.main.channel
		2. create the function for updating the channel.
		3. put the function into thread queue.
		4. go LOOP.
	"""

	SERVER_UPDATE = None

	def __init__ (self) :
		initLog( \
			config.zzim_update_log_level, config.zzim_update_file_log, \
			config.log["maxbyte"], config.log["backupcount"] \
		)
		self.log = logging.getLogger("ZZimClient")

		if config.zzim_update_log_level == "DEBUG" :
			self.log.info("gc.set_debug(gc.DEBUG_LEAK)")

		THREAD.__init__(self, config.zzim_update_max_thread_number)

	def start (self) :
		self.__start()

		return True

	def __start (self) :
		if self.getThreadCount() >= config.zzim_update_max_thread_number :
			reactor.callLater(1, self.__start)
			return

		__num = config.zzim_update_max_thread_number - self.getThreadCount()
		if __num < 1 :
			__num = config.zzim_update_max_thread_number

		__list = self.__readChannelList(__num)

		if len(__list) < 1 :
			# re-create tmp_channel table.
			try :
				self.__createChannelListTable()
			except Exception, e :
				self.log.debug(str(e))
				pass

			reactor.callLater(1, self.__start)
			return

		for __id in __list :
			self.log.debug("inserted %s" % __id)
			self.insert(self.__updateChannel, (__id, ))

		reactor.callLater(2, self.__start)

	def __readChannelList (self, num) :
		# read the channel list, which not updated yet
		__list = list( \
			model_tmp_channel.select( \
				orderBy=model_tmp_channel.q.timeUpdated, \
				reversed=False \
			).limit(num) \
		)

		__l = list()
		for i in __list :
			__l.append(i.id)
			i.destroySelf()

		return __l

	def __createChannelListTable (self) :
		# check whether table, tmp_channel is empty or not.
		if len(list(model_tmp_channel.select())) > 0 :
			return False

		__conn_main = database.get_connection(config.database["main"])
		__conn_main.queryOne( \
			QUERY_INSERT_INTO_TMP_CHANNEL % ( \
				str(datetime__.now(diff_minute=config.zzim_update_update_interval)) \
			) \
		)
		__conn_main.queryOne(QUERY_INSERT_INTO_TMP_CHANNEL_WIERD)

		return True

	def __updateChannel (self, id_channel) :
		__c = document_channel.Channel(id=id_channel)
		return __c.update()

"""
Description
-----------


ChangeLog
---------


Usage
-----


"""

__author__ =  "Spike^ekipS <spikeekips@gmail.com>"
__version__=  "0.1"
__nonsense__ = ""

__file__ = "service.py"


